import type { DataFormField } from '../DataField'
import type { DataFormDrawerProp } from '@/components/DataForm/types'
import { defineComponent, h, reactive, ref } from 'vue'
import DataFormDrawer from '@/components/DataForm/DataFormDrawer.vue'

export function useEditFormDrawer<T>({ editFields = [] }: {
  editFields: DataFormField[]
}) {
  const editFormData = ref<Partial<T>>({})
  const editFormVisible = ref(false)
  const editFormTitle = ref()
  const editFormSubmit = ref<((data: T) => Promise<any>)>()

  const editFormFields = reactive<DataFormField[]>(editFields)

  function openEditForm(title: string, data: Partial<T>, submit: (data: T) => Promise<any>) {
    editFormData.value = data
    editFormTitle.value = title
    editFormVisible.value = true
    editFormSubmit.value = submit
  }

  const EditFormDrawer = defineComponent(
    (props: DataFormDrawerProp<T>, { attrs, slots }) => {
      return () => h(DataFormDrawer<T>, {
        'fields': editFormFields,
        'formData': editFormData.value,
        'formVisible': editFormVisible.value,
        'onUpdate:formVisible': value => editFormVisible.value = value,
        'title': editFormTitle.value,
        'submit': editFormSubmit.value,
        ...props,
        ...attrs,
      }, slots)
    },
  )

  return {
    editFormData,
    openEditForm,
    editFormFields,
    editFormVisible,
    EditFormDrawer,
  }
}
